package com.banggood.upms.service.impl;

import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.exception.ExceptionEnum;
import com.banggood.upms.bean.po.Permission;
import com.banggood.upms.bean.po.SystemPo;
import com.banggood.upms.common.util.TimeUtils;
import com.banggood.upms.dao.PermissionDao;
import com.banggood.upms.dao.SystemDao;
import com.banggood.upms.dao.TreePermissionDao;
import com.banggood.upms.service.PermissionService;
import com.banggood.upms.service.SystemService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author XuChuangFeng
 */
@Service
@Transactional(rollbackFor = SkbException.class)
public class SystemServiceImpl extends BaseServiceImpl<SystemPo, SystemDao> implements SystemService {

    protected final Log logger = LogFactory.getLog(getClass());

    @Override
    @Autowired
    public void setDao(SystemDao dao) {
        super.dao = dao;
    }

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private TreePermissionDao treePermissionDao;

    /**
     * 调用添加系统的时候，需要导入该系统的权限配置
     */
    @Override
    public int insert(SystemPo sys) throws Exception {
        // 系统编码不允许重复
        if (dao.selectBySystemCode(sys.getCode()) != null) {
            throw new SkbException(ExceptionEnum.SYSTEM_CODE_DUPLICATED.getCode(), ExceptionEnum.SYSTEM_CODE_DUPLICATED.getMessage());
        }
        sys.setLastSyncTime(TimeUtils.getCurrentTimeStr());
        int flag = dao.insert(sys);
        int permCount = 0;
        if (flag > 0) {
            if (!CollectionUtils.isEmpty(sys.getPermissionList())) {
                permCount = permissionService.persistPermList(sys.getPermissionList());
            }
        }
        return flag + permCount;
    }

    /**
     * 权限码permissionCode相同视为同一个权限，可以修改权限的名字，状态等其他属性
     * @param system
     * @throws Exception
     */
    @Override
    public void refreshSysPermList(SystemPo system) throws Exception {
        int updateCount = 0;
        int addCount = 0;
        for (Permission permission : system.getPermissionList()) {
            int updateFlag = permissionService.updateByPrimaryKey(permission);
            if (updateFlag > 0) {
                updateCount += updateFlag;
            } else {
                //没有更新成功，添加
                int addFlag = permissionService.insert(permission);
                addCount += addFlag;
            }
        }
        system.setLastSyncTime(TimeUtils.getCurrentTimeStr());
        dao.updateByPrimaryKey(system);
    }

    @Override
    public int deleteByPrimaryKey(String id) throws Exception {
        SystemPo systemPo = dao.selectByPrimaryKey(id);
        if(systemPo == null) {
            throw new SkbException(ExceptionEnum.SYSTEM_NOT_EXISTS.getCode(), ExceptionEnum.SYSTEM_NOT_EXISTS.getMessage());
        }
        // 删除这个系统的权限已经被树节点分配的tree-perm
        List<String> permIds = permissionDao.selectPermIdsBySystemId(id);
        if (!permIds.isEmpty()) {
            int i = treePermissionDao.deleteAssignedTreePermByPermIds(permIds);
        }

        int deletedPermCount = permissionDao.deleteBySystemId(id);
        if (permIds.size() != deletedPermCount || deletedPermCount == 0) {
            throw new SkbException(ExceptionEnum.OPERATION_FAILED.getCode(), ExceptionEnum.OPERATION_FAILED.getMessage());
        }
        return dao.deleteByPrimaryKey(id);
    }
}
